package com.ddmmo.exhibition.common.annotation;

import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * <p>自定义日志注解切面类</p>
 * <p>注：如果 @WebLog 没有写描述信息，则看是否加了 Swagger 的 @ApiOperation 注解，如果加了则用其 value 属性值作为描述信息</p>
 */
@Slf4j
@Aspect
@Component
public class WebLogAspect {

    /**
     * 定义 @WebLog 注解为切点
     */
    @Pointcut("@annotation(com.ddmmo.exhibition.common.annotation.WebLog)")
    public void webLog() {

    }

    /**
     * 环绕
     */
    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        // 请求开始时间
        long startTime = System.currentTimeMillis();
        // 获取 HttpServletRequest
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
        // 获取描述信息：如果 @WebLog 没有写描述信息，则看是否加了 Swagger 的 @ApiOperation 注解，如果加了则用其 value 属性值作为描述信息
        String description = null;
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        WebLog webLog = method.getAnnotation(WebLog.class);
        if (webLog != null) {
            if (StringUtils.isNotBlank(webLog.description())) {
                description = webLog.description();
            } else {
                ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
                if (apiOperation != null) {
                    description = apiOperation.value();
                }
            }
        }

        // 打印请求相关参数
        log.info("========================================== Start ==========================================");
        // 打印请求 URL
        log.info("URL             : {}", request.getRequestURL().toString());
        // 打印请求接口描述信息
        log.info("Description     : {}", description);
        // 打印 Http method
        log.info("HTTP Method     : {}", request.getMethod());
        // 打印请求的 IP
        log.info("IP              : {}", request.getRemoteAddr());
        // 打印调用 Controller 的全路径以及执行方法
        log.info("Class Method    : {}.{}", signature.getDeclaringTypeName(), signature.getName());
        // 打印请求入参
        try {
            log.info("Class Method : {}, Request Args    : {}", signature.getDeclaringTypeName(), JSON.toJSONString(joinPoint.getArgs()));
        } catch (Exception e) {
            log.info("Request Args    : {}", "请求参数打印失败，可能是因为文件类型！");
        }

        // 执行切点
        Object result = joinPoint.proceed();

        // 打印出参
        log.info("Response Args   : {}", JSON.toJSONString(result));
        // 打印接口耗时
        log.info("Time Consuming  : {} ms", System.currentTimeMillis() - startTime);
        // 结束打印并换行（方便分割查看）
        log.info("=========================================== End ===========================================" + System.lineSeparator());
        // 返回接口返参结果
        return result;
    }

}
